const fs = require('fs')
const path = require('path')


const splitJsFile = content => {
	const result = content.match(/require\(.*\)/g)
	if(result){

		const last = result.pop()

		const lastIndex = content.lastIndexOf(last)

		const splitPosition = lastIndex+last.length

		return [content.substring(0,splitPosition),content.substring(splitPosition,content.length)]
	}
	return ["",content]
}


class File {

	content="";
	encoding = 'utf-8'

	constructor(fsPath){
		this.fsPath = fsPath;
	}

	getExtName(){
		return path.extname(this.fsPath);
	}

	getFileName(noExt){
		const name =  path.basename(this.fsPath)
		return noExt ? name.split(".")[0] : name;
	}

	getFileDir(){
		return path.dirname(this.fsPath);
	}

	getRelativeFile(relativePath){
		return new File(path.join(this.getFileDir(),relativePath))
	}

	readFile(){
		this.content = fs.readFileSync(this.fsPath,this.encoding).toString()
		return this;
	}

	setContent(c){
		this.content = c;
		return this;
	}

	writeFile(){
		const {encoding} = this;
		fs.writeFileSync(this.fsPath,this.content,{encoding})
	}

	append(add){
		return this.setContent(this.content+add+";\n")
	}

	appendFile(filePath){
		return this.setContent(this.content+new File(filePath).readFile().content+";");
	}

	preAppendFile(filePath){
		return this.setContent(new File(filePath).readFile().content+this.content+";");
	}

	delete(){
		if(fs.existsSync(this.fsPath))
			fs.rmSync(this.fsPath)
	}

	isContain(str){
		return this.content.indexOf(str) > -1;
	}

	mapRows(fn){
		this.content = this.content.split('\n').map(fn).join('\n');
		return this;
	}

}




class CompileFile extends File{

	constructor(fsPath){
		super(fsPath)
	}

	//创建同目录文件
	createFileInCurrentDir(fileName){
		const targetPath = path.join(this.getFileDir(),fileName)
		return new CompileFile(targetPath)
	}

	//创建同目录同名文件，但后缀不同
	createLikeFile(ext){
		const targetPath = path.join(this.getFileDir(),this.getFileName().split(".")[0]+ext)
		return new CompileFile(targetPath)
	}

	//替换文件中的内容
	replaceAll(key,fn){
		return this.setContent(this.content.replace(new RegExp(key,"gm"),fn))
	}

	replace(k,v){
		return this.setContent(this.content.replace(k,v))
	}

	static of(fsPath){
		return new CompileFile(fsPath).readFile()
	}

	//添加js文件 提升require
	appendJsFile(cf){
		const [h1,c1] = splitJsFile(this.content)
		const [h2,c2] = splitJsFile(cf.content)
		return this.setContent(h1+"\n"+h2).append(c1+"\n"+c2)
	}

	appendAsyncWrapStar(){
		return this.append("(global.__runWrapFunction_ = async ()=>{  ")
	}

	appendAsyncWrapEnd(){
		return this.append("})().catch(OVER_EVENT)")
	}

	//包裹异步代码
	appendAsyncWrap(code){
		return this.appendAsyncWrapStar().append(code).appendAsyncWrapEnd()
	}

}




module.exports = {CompileFile}